<template>
  <div class="device-management-view">
    <!-- 搜索区域 -->
    <div class="search-bar">
      <div class="search-area">
        <el-input
          v-model="searchKeyword"
          placeholder="请输入设备名称"
          prefix-icon="el-icon-search"
          size="small"
          style="width: 250px;"
          clearable
          @keyup.enter.native="handleSearch"
        ></el-input>
        <el-select
          v-model="factoryFilter"
          placeholder="请选择工厂"
          size="small"
          style="width: 200px; margin-left: 10px;"
          clearable
        >
          <el-option label="全部工厂" :value="''"></el-option>
          <el-option 
            v-for="factory in factoryList" 
            :key="factory.id" 
            :label="factory.factory_name" 
            :value="factory.id"
          ></el-option>
        </el-select>
        <el-button type="primary" size="small" style="margin-left: 10px;" @click="handleSearch">搜索</el-button>
        <el-button size="small" @click="resetSearch">重置</el-button>
      </div>
      <div class="operation-area">
        <el-button type="primary" size="small" @click="handleAdd">新增设备</el-button>
      </div>
    </div>

    <!-- 设备列表表格 -->
    <el-table 
      :data="deviceList" 
      style="width: 100%; margin-top: 20px;" 
      border 
      v-loading="loading"
    >
      <el-table-column label="序号" width="60px" align="center">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="device_name" label="设备名称" width="120px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.device_name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属工厂" width="200px" align="center">
        <template slot-scope="scope">
          <div v-if="scope.row.factory">
            <div>{{ scope.row.factory.factory_name }}</div>
            <div style="font-size: 12px; color: #999;">{{ scope.row.factory.address }}</div>
          </div>
          <span v-else style="color: #999;">无</span>
        </template>
      </el-table-column>
      <el-table-column label="流量卡需求" width="120px" align="center">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.is_need" type="warning" size="mini">需要流量卡</el-tag>
          <el-tag v-else type="info" size="mini">无需流量卡</el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column label="显示顺序" width="100px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.list_order || '-' }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="配件信息" min-width="300px">
        <template slot-scope="scope">
          <div v-if="scope.row.accessories && scope.row.accessories.length > 0" class="accessories-display">
            <div v-for="accessory in scope.row.accessories" :key="accessory.id" class="accessory-item">
              <el-tag 
                size="mini"
                class="accessory-name-tag"
                type="primary"
              >
                {{ accessory.accessory_name }}
              </el-tag>
            </div>
          </div>
          <div v-else style="color: #999; font-size: 12px;">无配件</div>
        </template>
      </el-table-column>
      
      <!-- 操作列 -->
      <el-table-column label="操作" width="180px" align="center">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" size="small" style="color: #F56C6C;" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
      >
      </el-pagination>
    </div>

    <!-- 新增/编辑设备弹窗 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
      center
    >
      <el-form :model="form" :rules="formRules" ref="form" label-width="120px">
        <el-form-item label="设备名称" prop="device_name">
          <el-input 
            v-model="form.device_name" 
            placeholder="请输入设备名称"
            maxlength="50"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="所属工厂" prop="factory_id">
          <el-select 
            v-model="form.factory_id" 
            placeholder="请选择所属工厂"
            style="width: 100%;"
          >
            <el-option 
              v-for="factory in factoryList" 
              :key="factory.id" 
              :label="factory.factory_name" 
              :value="factory.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="流量卡需求" prop="is_need">
          <el-radio-group v-model="form.is_need">
            <el-radio :label="1">
              <el-tag type="warning" size="mini">需要流量卡</el-tag>
            </el-radio>
            <el-radio :label="0">
              <el-tag type="info" size="mini">无需流量卡</el-tag>
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="显示顺序" prop="list_order">
          <el-input-number 
            v-model="form.list_order" 
            :min="1" 
            :max="9999"
            placeholder="请输入显示顺序"
            style="width: 100%;"
          ></el-input-number>
          <div style="font-size: 12px; color: #909399; margin-top: 4px;">
            数字越小排序越靠前，建议使用1-9999之间的数字
          </div>
        </el-form-item>
        <el-form-item label="配件信息" prop="selectedAccessories">
          <div class="accessories-container" v-loading="accessoryLoading">
            <div v-for="accessory in accessoryList" :key="accessory.id" class="accessory-select-item">
              <div class="accessory-checkbox">
                <el-checkbox 
                  v-model="accessory.selected" 
                  @change="handleAccessorySelectionChange(accessory)"
                >
                  <div class="accessory-info">
                    <div class="accessory-name">{{ accessory.accessory_name }}</div>
                    <el-tooltip 
                      v-if="accessory.describe_info" 
                      :content="accessory.describe_info" 
                      placement="top" 
                      :show-after="500"
                      popper-class="accessory-desc-tooltip"
                    >
                      <div class="accessory-desc">{{ accessory.describe_info }}</div>
                    </el-tooltip>
                    <div v-else class="accessory-desc">无描述信息</div>
                  </div>
                </el-checkbox>
              </div>
              <div v-if="accessory.selected" class="accessory-config">
                <el-radio-group v-model="accessory.is_standard" size="mini">
                  <el-radio :label="1">
                    <el-tag type="success" size="mini">标配</el-tag>
                  </el-radio>
                  <el-radio :label="0">
                    <el-tag type="warning" size="mini">选配</el-tag>
                  </el-radio>
                </el-radio-group>
              </div>
            </div>
            <div v-if="accessoryList.length === 0 && !accessoryLoading" class="no-accessories">
              <span style="color: #999; font-size: 12px;">暂无配件数据</span>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitLoading">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getDeviceList, getFactoryList, addDevice, editDevice, deleteDevice, accessoryListTwo } from '@/api/contract';
import { checkToken, handleTokenExpired, checkTokenFromError } from '@/utils/auth';

export default {
  name: 'DeviceManagementView',
  data() {
    return {
      // 搜索相关
      searchKeyword: '',
      factoryFilter: '',
      
      // 表格数据
      deviceList: [],
      factoryList: [],
      accessoryList: [],
      loading: false,
      
      // 分页相关
      currentPage: 1,
      pageSize: 10,
      total: 0,

      // 弹窗相关
      dialogVisible: false,
      dialogTitle: '新增设备',
      isEdit: false,
      submitLoading: false,
      
             // 表单数据
       form: {
         id: '',
         device_name: '',
         factory_id: '',
         is_need: 0,
         list_order: 1
       },
       
       // 原始配件列表（用于编辑时检测删除的配件）
       originalAccessories: [],
       
       // 配件加载状态
       accessoryLoading: false,
      
      // 表单验证规则
      formRules: {
        device_name: [
          { required: true, message: '请输入设备名称', trigger: 'blur' },
          { min: 1, max: 50, message: '设备名称长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        factory_id: [
          { required: true, message: '请选择所属工厂', trigger: 'change' }
        ],
        is_need: [
          { required: true, message: '请选择流量卡需求', trigger: 'change' }
        ],
        list_order: [
          { required: true, message: '请输入显示顺序', trigger: 'blur' },
          { type: 'number', min: 1, max: 9999, message: '显示顺序必须在1-9999之间', trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    // 获取设备列表
    async fetchDeviceList() {
      this.loading = true;
      try {
        // 检查token是否存在
        if (!checkToken()) {
          this.$message.error('登录已过期，请重新登录');
          handleTokenExpired();
          return;
        }

        const params = {
          keyword: this.searchKeyword,
          factory_id: this.factoryFilter,
          page: this.currentPage,
          pageSize: this.pageSize
        };
        
        const response = await getDeviceList(params);
        
        if (response.data && response.data.code === 1) {
          // API成功返回数据
          let deviceList = response.data.data.items || [];
          // 按照list_order字段排序，数字越小排序越靠前
          deviceList.sort((a, b) => {
            const orderA = a.list_order || 9999;
            const orderB = b.list_order || 9999;
            return orderA - orderB;
          });
          this.deviceList = deviceList;
          this.total = response.data.data.total || 0;
        } else {
          this.$message.error(response.data.msg || '获取设备列表失败');
        }
      } catch (error) {
        console.error('获取设备列表失败:', error);
        if (checkTokenFromError(error)) {
          // Token无效或过期
          this.$message.error('登录已过期，请重新登录');
          handleTokenExpired();
        } else {
          // 其他错误
          this.$message.error('获取设备列表失败');
        }
      } finally {
        this.loading = false;
      }
    },

    // 获取工厂列表
    async fetchFactoryList() {
      try {
        const response = await getFactoryList({});
        if (response.data && response.data.code === 1) {
          this.factoryList = response.data.data.data || [];
        }
      } catch (error) {
        console.error('获取工厂列表失败:', error);
      }
    },
    
    // 获取配件列表
    async fetchAccessoryList() {
      this.accessoryLoading = true;
      try {
        // 检查token是否存在
        if (!checkToken()) {
          this.$message.error('登录已过期，请重新登录');
          handleTokenExpired();
          return;
        }

        const response = await accessoryListTwo({});
        if (response.data && response.data.code === 1) {
          // 为每个配件添加选中状态和标配/选配属性
          this.accessoryList = (response.data.msg || []).map(accessory => ({
            ...accessory,
            selected: false,
            is_standard: 1 // 默认标配
          }));
          
          // 调试信息
          console.log('配件列表加载完成:', this.accessoryList);
        } else {
          this.$message.error(response.data.msg || '获取配件列表失败');
        }
      } catch (error) {
        console.error('获取配件列表失败:', error);
        if (checkTokenFromError(error)) {
          this.$message.error('登录已过期，请重新登录');
          handleTokenExpired();
        } else {
          this.$message.error('获取配件列表失败');
        }
      } finally {
        this.accessoryLoading = false;
      }
    },
    
    // 初始化配件选择
    initSelectedAccessories(accessories) {
      console.log('初始化配件选择，传入的配件:', accessories);
      console.log('当前配件列表:', this.accessoryList);
      
      if (accessories && accessories.length > 0) {
        // 为每个配件设置选中状态和标配/选配属性
        this.accessoryList.forEach(accessory => {
          const existingAccessory = accessories.find(item => item.id === accessory.id);
          if (existingAccessory) {
            accessory.selected = true;
            accessory.is_standard = existingAccessory.is_standard !== undefined ? existingAccessory.is_standard : 1; // 默认标配
            console.log(`配件 ${accessory.accessory_name} 已选中，设置为${accessory.is_standard === 1 ? '标配' : '选配'}`);
          } else {
            accessory.selected = false;
            accessory.is_standard = 1; // 默认标配
          }
        });
      } else {
        // 重置所有配件为未选中状态
        this.accessoryList.forEach(accessory => {
          accessory.selected = false;
          accessory.is_standard = 1; // 默认标配
        });
        console.log('重置所有配件为未选中状态');
      }
      
      console.log('初始化完成后的配件列表:', this.accessoryList);
    },
    
    // 处理配件选择变化
    handleAccessorySelectionChange(accessory) {
      if (accessory.selected) {
        // 选中时默认设置为标配
        accessory.is_standard = 1;
      }
    },
    
    // 获取选中的配件数据
    getSelectedAccessories() {
      return this.accessoryList
        .filter(accessory => accessory.selected)
        .map(accessory => ({
          id: accessory.id,
          accessory_name: accessory.accessory_name,
          is_standard: accessory.is_standard
        }));
    },
    
    // 搜索
    handleSearch() {
      this.currentPage = 1;
      this.fetchDeviceList();
    },
    
    // 重置搜索
    resetSearch() {
      this.searchKeyword = '';
      this.factoryFilter = '';
      this.currentPage = 1;
      this.fetchDeviceList();
    },
    
    // 分页大小改变
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.fetchDeviceList();
    },
    
    // 当前页改变
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchDeviceList();
    },

    // 新增设备
    handleAdd() {
      this.dialogTitle = '新增设备';
      this.isEdit = false;
      this.form = {
        id: '',
        device_name: '',
        factory_id: '',
        is_need: 0,
        list_order: 1
      };
      // 获取配件列表
      this.fetchAccessoryList();
      this.dialogVisible = true;
      // 清除表单验证
      this.$nextTick(() => {
        this.$refs.form && this.$refs.form.clearValidate();
      });
    },

         // 编辑设备
     async handleEdit(row) {
       this.dialogTitle = '编辑设备';
       this.isEdit = true;
       
       // 保存原始配件列表，用于检测删除的配件
       this.originalAccessories = row.accessories ? [...row.accessories] : [];
       
       this.form = {
         id: row.id,
         device_name: row.device_name,
         factory_id: row.factory_id,
         is_need: row.is_need,
         list_order: row.list_order || 1
       };
       
       // 先获取配件列表，等待完成后再初始化选中的配件
       await this.fetchAccessoryList();
       
       // 初始化选中的配件
       this.initSelectedAccessories(row.accessories);
       
       this.dialogVisible = true;
       // 清除表单验证
       this.$nextTick(() => {
         this.$refs.form && this.$refs.form.clearValidate();
       });
     },

         // 删除设备
     async handleDelete(row) {
       try {
         await this.$confirm(`确定要删除设备"${row.device_name}"吗？`, '提示', {
           confirmButtonText: '确定',
           cancelButtonText: '取消',
           type: 'warning'
         });
         
         // 检查token是否存在
         if (!checkToken()) {
           this.$message.error('登录已过期，请重新登录');
           handleTokenExpired();
           return;
         }
         
         // 调用删除设备API
         const response = await deleteDevice(row.id);
         
         if (response.data && response.data.code === 1) {
           this.$message.success('删除设备成功');
           // 重新加载设备列表
           this.fetchDeviceList();
         } else {
           this.$message.error(response.data.msg || '删除设备失败');
         }
       } catch (error) {
         if (error === 'cancel') {
           this.$message.info('已取消删除');
         } else {
           console.error('删除设备失败:', error);
           if (checkTokenFromError(error)) {
             this.$message.error('登录已过期，请重新登录');
             handleTokenExpired();
           } else {
             this.$message.error('删除设备失败');
           }
         }
       }
     },

    

    // 提交表单
    async submitForm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          this.submitLoading = true;
          try {
            // 检查token是否存在
            if (!checkToken()) {
              this.$message.error('登录已过期，请重新登录');
              handleTokenExpired();
              return;
            }

            const submitData = {
              device_name: this.form.device_name.trim(),
              factory_id: this.form.factory_id,
              is_need: this.form.is_need,
              list_order: this.form.list_order,
              accessories: this.getSelectedAccessories()
            };

            if (this.isEdit) {
              submitData.id = this.form.id;
            }

            // 调试信息
            console.log('提交数据:', submitData);

            const response = this.isEdit ? await editDevice(submitData) : await addDevice(submitData);

            if (response.data && response.data.code === 1) {
              this.$message.success(this.isEdit ? '编辑设备成功' : '新增设备成功');
              this.dialogVisible = false;
              this.fetchDeviceList();
            } else {
              this.$message.error(response.data.msg || (this.isEdit ? '编辑设备失败' : '新增设备失败'));
            }
          }
           catch (error) {
            console.error('提交设备信息失败:', error);
            if (checkTokenFromError(error)) {
              this.$message.error('登录已过期，请重新登录');
              handleTokenExpired();
            } else {
              this.$message.error('操作失败');
            }
          } finally {
            this.submitLoading = false;
          }
        }
      });
    }
  },
  
  created() {
    this.fetchFactoryList();
    this.fetchDeviceList();
  }
};
</script>

<style scoped>
.device-management-view {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 60px);
  box-sizing: border-box;
}

.search-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-area {
  display: flex;
  align-items: center;
}

.operation-area {
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  text-align: right;
}

/* 表格样式 */
.el-table {
  border: 1px solid #EBEEF5;
}

.el-table th {
  background-color: #f5f7fa !important;
  color: #606266;
}

.el-table td, .el-table th {
  border-bottom: 1px solid #EBEEF5;
  border-right: 1px solid #EBEEF5;
}

.el-table th:last-child,
.el-table td:last-child {
  border-right: none;
}

/* 配件选择样式 */
.accessories-container {
  border: 1px solid #DCDFE6;
  border-radius: 4px;
  padding: 15px;
  background-color: #fafafa;
  max-height: 300px;
  overflow-y: auto;
}

.accessory-select-item {
  margin-bottom: 15px;
  padding: 10px;
  border: 1px solid #E4E7ED;
  border-radius: 4px;
  background-color: #fff;
}

.accessory-checkbox {
  display: flex;
  align-items: flex-start;
  margin-bottom: 8px;
}

.accessory-info {
  margin-left: 10px;
  flex: 1;
}

.accessory-name {
  font-weight: 500;
  color: #303133;
}

.accessory-desc {
  color: #909399;
  font-size: 12px;
  margin-top: 2px;
  max-width: 300px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  cursor: pointer;
}

.accessory-config {
  margin-left: 26px;
  padding-top: 8px;
  border-top: 1px solid #F0F0F0;
}

.no-accessories {
  text-align: center;
  padding: 20px;
}

/* 配件信息显示样式 */
.accessories-display {
  padding: 8px 0;
}

.accessory-item {
  display: inline-block;
  margin-right: 8px;
  margin-bottom: 4px;
}

.accessory-name-tag {
  white-space: nowrap;
}
</style>

<style>
/* 全局tooltip样式 */
.accessory-desc-tooltip {
  max-width: 400px !important;
  word-break: break-all;
  line-height: 1.5;
  font-size: 12px;
  padding: 8px 12px;
}

.accessory-desc-tooltip .el-tooltip__popper {
  background-color: #303133;
  color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style>